package com.rfs.design.chain;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.rfs.dto.ResponseDTO;
import lombok.Data;

import java.util.List;
import java.util.Map;

/**
 * @author renfushuai
 * @date 2022/8/29
 */
@Data
public class ProcessController {
    /**
     * 模板映射
     */
    private Map<String, ProcessTemplate> templateConfig = null;

    public ProcessContext process(ProcessContext context) {

        /**
         * 前置检查
         */
        try {
            preCheck(context);
        } catch (Exception e) {
            context = new ProcessContext();
            context.setResponse(ResponseDTO.error(500,e.getMessage()));
            return context;
        }
        /**
         * 遍历流程节点
         */
        List<BusinessProcess> processList = templateConfig.get(context.getCode()).getProcessList();
        for (BusinessProcess businessProcess : processList) {
            businessProcess.process(context);
            if (context.getNeedBreak()) {
                break;
            }
        }
        return context;
    }
    private void preCheck(ProcessContext context) throws Exception {
        // 上下文
        if (context == null) {
            throw new Exception("流程上下文为空");
        }

        // 业务代码
        String businessCode = context.getCode();
        if (StrUtil.isBlank(businessCode)) {
            throw new Exception("业务代码为空");
        }

        // 执行模板
        ProcessTemplate processTemplate = templateConfig.get(businessCode);
        if (processTemplate == null) {
            throw new Exception("流程模板配置为空");
        }

        // 执行模板列表
        List<BusinessProcess> processList = processTemplate.getProcessList();
        if (CollUtil.isEmpty(processList)) {
            throw new Exception("业务处理器配置为空");
        }

    }
}
